import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:top_foundation/component/page_state/widgets/empty.dart';
import 'package:top_foundation/utils/theme/theme.dart';

import '../../../utils/util.dart';
import 'controller.dart';

typedef ViewBodyBuilder = Widget Function(BuildContext context, Widget child);

abstract class IRefreshView<T extends IRefreshController> extends GetView<T> {
  const IRefreshView({super.key});

  @protected
  Widget buildEmpty(BuildContext context) {
    return const EmptyView();
  }

  @protected
  Widget buildRefreshBody(BuildContext context);
  @protected
  Widget buildView(BuildContext context, Widget refreshBody);

  Widget buildRefreshContainer(BuildContext context) {
    var state = controller.state;
    return GetBuilder<T>(
        id: state.updateBodyId,
        builder: (_) {
          return (state.page?.records?.isNotEmpty == true ||
                  state.dataModel != null)
              ? buildRefreshBody(context)
              : buildEmpty(context);
        });
  }

  Widget buildRefreshView(BuildContext context) {
    var state = controller.state;
    return EasyRefresh(
      header: CupertinoHeader(foregroundColor: ITheme.selectedColor),
      controller: state.controller,
      onRefresh: controller.onRefresh,
      onLoad: state.enablePullup ? controller.onLoading : null,
      child: buildRefreshContainer(context),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<T>(
      builder: (controller) {
        return buildView(
          context,
          buildRefreshView(
            context,
          ),
        );
      },
    );
  }
}
